<?php
if (!class_exists('UserManager')) {
	require_once 'lib/PasswordHash.php';
	
	/**
	 * User manager bussiness logic object
	 * @author Alecsandru Gabriel DINU
	 * @since Jun 27, 2008
	 * 
 	 * @Bean(id = "userManager") 
 	 * @Property(name = "userDao", ref="userDao")  
	 */
	class UserManager {
		private $dao;
		
		/**
		 * Sets the UserDao
		 * @param UserDao
		 */
		public function setUserDao($dao) {
			$this->dao = $dao;	
		}
		
		/**
		 * Returns a list with all the users
		 * @access public
		 * @param boolean Include only active users ?
		 * @return array List of users
		 */
		public function getAll($onlyActive = true) {
			return $this->dao->getAll($onlyActive);	
		}
		
		/**
		 * Saves a user in the database
		 * @param User
		 * @access public
		 */
		public function save(User $user) {
			Validate::notNull($user, "User cannot be null/");
			if (! ($user instanceof User)) {
				throw new IllegalArgumentException("'user' parameter must be an instance of User class");
			}
			
			try {
				Validate::notEmpty($user->getEmail(), "User email is empty.");
				Validate::checkEmail($user->getEmail(), "User email is invalid.");
			} catch (IllegalArgumentException $e) {
				throw new BadEmailException($e);	
			}
			
			
			if ($user->getId() != null) {
				$edited_user = $user; 
				$user = $this->dao->get($user->getId());
				
				$user->setName($edited_user->getName());
				$user->setPhone($edited_user->getPhone());
				$user->setActive($edited_user->getActive());
			} else {
				Validate::notEmpty($user->getPass(), "Password is empty");				
				
				$user->setActive(1);
				$user->setRegisterDate(time());
				
				// hash password
				$t_hasher = new PasswordHash(8, FALSE);
				$hash = $t_hasher->HashPassword($user->getPass());
				$user->setPass($hash);
				
				// setup roles
				if (sizeof($user->getUserrolesJoinRole()) == 0) {
					$roleManager = new RoleManager();
					$role = $roleManager->get("user");
					$userrole = new Userrole();
					$userrole->setRole($role);
					$userrole->setUser($user);
					$user->addUserrole($userrole);
				}	
			}
			
			
			$this->dao->save($user);
			
		}
		
		/**
		 * Gets a user base on his id
		 * @param integer
		 * @access public
		 * @return User
		 */
		public function getById($id) {
			return $this->dao->get($id);
		}

		/**
		 * Perform user login. If the login is successful , it also
		 * stores user data in session.
		 * @access public
		 * @param Context
		 * @param User
		 * @return boolean
		 */
		public function login(Context $context, User $user) {
			Validate::notNull($user, "User cannot be null");
			Validate::notNull($context, "Session cannot be null");
			if (! ($user instanceof User)) {
				throw new InvalidArgumentException("'user' parameter must be an instance of User class");
			}
			Validate::notEmpty($user->getEmail(), "User email is empty");
			Validate::notEmpty($user->getPass(), "Password is empty");
			
			$existing = $this->dao->loadByEmail($user->getEmail());
			if ($existing == null) {
				return false;
			}

			// check password hash
			$t_hasher = new PasswordHash(8, FALSE);
			$pass_check = $t_hasher->CheckPassword($user->getPass(), $existing->getPass());
			if (!$pass_check) {
				return false;
			}
			
			// authentication was successful	
					
			$context->setUser(array (
				"id" => $existing->getId(),
				"email" => $existing->getEmail(),
				"name" => $existing->getName(),
				"phone" => $existing->getPhone(),
			));
			
			$roles = array();
			$userroles = $existing->getUserrolesJoinRole();
			foreach ($userroles as $userrole) {
				$roles[] = $userrole->getRole()->getName();
			}
			$context->setRoles($roles);
			return true;
		}
		
		/**
		 * Removes the user data from session.
		 * @access public
		 * @param Context
		 */
		public function logout(Context $context) {
			$context->setRoles(null);
			$context->setUser(null);
		}
		
	}
}
?>